// 实现异步缓冲区
#pragma once
#include "util.hpp"
#include <vector>
#include <assert.h>

namespace LOG
{
#define DEFAULTSIZE (1024*1024 )

    class Buffer
    {
    public:
        Buffer() : _buffer(DEFAULTSIZE), _reader_size(0), _writer_size(0) {};
        void push(const char *data, size_t len)
        {
            // 1 判断是否可以写入 有两种方式一种直接退出，一种先扩容
            //if(len+_writer_size > writeAbleSize()){return ;};
            ensureEnoughSize(len);
            // 2 将数据拷贝到缓冲区
            copy(data, data + len, &_buffer[_writer_size]);
            moveWrite(len);
        }
        size_t writeAbleSize()
        {
            return (_buffer.size() - _writer_size);
        }
        const char *begin()
        {
            return &_buffer[_reader_size];
        }
        size_t readeAbleSize()
        {
            return _writer_size - _reader_size;
        }
        void moveReader(size_t len)
        {
            assert(len < readeAbleSize());
            _reader_size += len;
        }
        void reset()
        {
            _writer_size = 0;
            _reader_size = 0;
        }
        void Swap(Buffer &buffer) //这里不传引用，用临时对戏那个怕是交换有问题呀。。。。
        {
            _buffer.swap(buffer._buffer);
            swap(_reader_size,buffer._reader_size);
            swap(_writer_size,buffer._writer_size);
        }
        bool empty()
        {
            if (_reader_size == _writer_size) {
                std::cout << _reader_size << " - " << _writer_size << " 无数据可读\n";
            }
            return (_reader_size == _writer_size);

        }
private:
        //是否需要扩容
        void ensureEnoughSize(size_t len)
        {
            if(len > writeAbleSize())
            {
                //线性增长
                _buffer.resize(_buffer.size()+len);
            }

        }
        void moveWrite(size_t len)
        {
            assert(len+_writer_size <=_buffer.size());
            _writer_size += len;
        }
    public:
        vector<char> _buffer;
        size_t _reader_size;
        size_t _writer_size;
    };

}